import grails.converters.*

//FIXME add access control for ajax calls
class DevicegroupController {

    def authenticateService

    def index = {redirect(action: list, params: params)}

    // the delete, save and update actions only accept POST requests
    def allowedMethods = [delete: 'POST', save: 'POST', update: 'POST']

    def getGeozonesAjax = {
        if (!params.id) {
            render [] as JSON
        }

        def dg = Devicegroup.get(params.id)
        if (!dg) {
            println "device not found with id ${params.id}"
            render [] as JSON
        } else {
            def zones = dg.geozones
            def results = []

            render zones.collect {
                zone -> zone.points
            } as JSON
            // render results as JSON
        }
    }

    //FIXME report2KML
    
    def report2XML = {
        def devicegroup = Devicegroup.get(params.id)
        if (!devicegroup) {
            render "Device not found with id ${params.id}"
        }
        else {
            def devices = devicegroup.devices;
            render devices.collect {
                device ->
                Eventdata.findAllByDevice(device, [max: 100,
                        sort: "timestamp",
                        order: "desc"])
            } as XML
        }
    }


    def trackAjaxCurrent = {
        def devicegroup = Devicegroup.get(params.id)
        if (!devicegroup) {
            render "Device not found with id ${params.id}"
        }
        else {
            def devices = devicegroup.devices;
            render devices.collect {
                device ->
                Eventdata.findAllByDevice(device, [max: 100,
                        sort: "timestamp",
                        order: "desc"])
            } as JSON
        }
    }

    def trackAjax = {
        println "trackAjax"
        println params
        def devicegroup = Devicegroup.get(params.id)
        if (!devicegroup) {
            render "Device not found with id ${params.id}"
        }
        else {
            def devices = devicegroup.devices;
            if (params.dt && params.df) {
                println "updating map"
                render devices.collect {
                    device ->
                    Eventdata.findAllByDeviceAndTimestampBetween(device, new Date(Long.parseLong(params.df)), new Date(Long.parseLong(params.dt)), [max: 100,
                            sort: "timestamp",
                            order: "desc"])
                } as JSON
            } else {
                println "default map"
                render devices.collect {
                    device ->
                    Eventdata.findAllByDevice(device, [max: 100,
                            sort: "timestamp",
                            order: "desc"])
                } as JSON
            }

        }
    }

    def current = {
        if (!params.id) {
            flash.message = "Devicegroup id not provided"
            redirect(action: list)
        } else {
            def devicegroup = Devicegroup.get(params.id)
            if (!devicegroup) {
                flash.message = "devicegroup not found with id ${params.id}"
                redirect(action: list)
            }
            else {return [devicegroup: devicegroup]}
        }
    }




    def list = {
        println params
        if (authenticateService.ifAllGranted("ROLE_ADMIN")) {
            if (!params.max) params.max = 10
            return [devicegroupList: Devicegroup.list(params)]
        } else if (authenticateService.ifAllGranted("ROLE_USER")) {
            return [devicegroupList: Devicegroup.findAllByUser(authenticateService.userDomain())]
        }

    }

    def show = {
        def devicegroup = Devicegroup.get(params.id)
        if (devicegroup) {
            if (authenticateService.ifAllGranted("ROLE_ADMIN")) {
                if (!devicegroup) {
                    flash.message = "Devicegroup not found with id ${params.id}"
                    redirect(action: list)
                }
                else {return [devicegroup: devicegroup]}
            } else if (authenticateService.ifAllGranted("ROLE_USER")) {
                if (devicegroup.user.id == authenticateService.userDomain().id) {
                    return [devicegroup: devicegroup]
                } else {
                    flash.message = "Devicegroup not found with id ${params.id}"
                    redirect(action: list)
                }
            }
        } else {
            flash.message = "Devicegroup not found with id ${params.id}"
            redirect(action: list)
        }
    }

    def delete = {
        def devicegroup = Devicegroup.get(params.id)
        if (devicegroup) {
            if (authenticateService.ifAllGranted("ROLE_ADMIN")) {
                devicegroup.delete()
                flash.message = "Devicegroup ${params.id} deleted"
                redirect(action: list)
            } else if (authenticateService.ifAllGranted("ROLE_USER")) {
                if (devicegroup.user.id == authenticateService.userDomain().id) {
                    devicegroup.delete()
                    flash.message = "Devicegroup ${params.id} deleted"
                    redirect(action: list)
                } else {
                    flash.message = "Devicegroup not found with id ${params.id}"
                    redirect(action: list)
                }
            } else {
                flash.message = "Devicegroup not found with id ${params.id}"
                redirect(action: list)
            }
        }
    }


    def edit = {
        def devicegroup = Devicegroup.get(params.id)
        if (!devicegroup) {
            flash.message = "Devicegroup not found with id ${params.id}"
            redirect(action: list)
        }
        else {
            if (authenticateService.ifAllGranted("ROLE_ADMIN")) {
                return [devicegroup: devicegroup]
            } else if (authenticateService.ifAllGranted("ROLE_USER")) {
                if (devicegroup.user.id == authenticateService.userDomain().id) {
                    return [devicegroup: devicegroup]
                } else {
                    flash.message = "Devicegroup not found with id ${params.id}"
                    redirect(action: list)
                }

            }

        }
    }

    def update = {
        def devicegroup = Devicegroup.get(params.id)
        if (devicegroup) {
            devicegroup.properties = params
            if (!devicegroup.hasErrors() && devicegroup.save()) {
                flash.message = "Devicegroup ${params.id} updated"
                redirect(action: show, id: devicegroup.id)
            }
            else {
                render(view: 'edit', model: [devicegroup: devicegroup])
            }
        }
        else {
            flash.message = "Devicegroup not found with id ${params.id}"
            redirect(action: edit, id: params.id)
        }
    }

    def create = {
        def devicegroup = new Devicegroup()
        devicegroup.properties = params
        return ['devicegroup': devicegroup]
    }

    def save = {
        def devicegroup = new Devicegroup(params)

        def user = null;

        if (authenticateService.ifAllGranted("ROLE_ADMIN")) {
            user = User.get(params.user.id)
        } else {
            user = authenticateService.userDomain();
        }

        devicegroup.user = user;

        if (!devicegroup.hasErrors() && devicegroup.save()) {
            flash.message = "Devicegroup ${devicegroup.id} created"
            redirect(action: show, id: devicegroup.id)
        }
        else {
            render(view: 'create', model: [devicegroup: devicegroup])
        }
    }
}